using Microsoft.AspNetCore.Builder;
using Elasticsearch.Net;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MT.Enterprise.Utils.Extensions;
using Newtonsoft.Json;
using NP.BPMReportPlatform.Common;
using NP.BPMReportPlatform.Contract;
using NP.BPMReportPlatform.Contract.Dtos;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.ElectronicSign;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Entities.BPM_Platform.Contract;
using NP.BPMReportPlatform.RecurringJobs;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using NP.BPMReportPlatform.SF.Dto;
using NP.Enterprise.Utils.HanaOdbc;
using NP.Enterprise.Utils.Http;
using RestSharp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using static NP.BPMReportPlatform.Contract.Dtos.ContractEnum;
using static NP.BPMReportPlatform.SF.Dto.SFDto;
using NP.BPMReportPlatform.Leave.Dto;
using NPOI.HSSF.Record.Chart;
using System.Threading;
using System.Collections.Specialized;
using System.Web;
using NP.BPMReportPlatform.Entities.BPM_Business;
using DocumentFormat.OpenXml.InkML;
using System.Text.RegularExpressions;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using SQLitePCL;
using NPOI.HPSF;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using DocumentFormat.OpenXml.Office2010.Excel;

namespace NP.BPMReportPlatform.SF
{
    /// <summary>
    /// SF同步接口
    /// </summary>
    public class SFSyncJD : BpmReportPlatformRecurringJob, ISFSyncJD
    {
        private readonly INPRestHttpHelper _nPRestHttp;
        private readonly SqlSugarClient _db, _dbPlatform;
        private readonly string _sourceSystem = "BPMNEW";
        private readonly string _esbSFGetUrl2;

        public SFSyncJD(ISqlSugarAppService sqlSugarAppService,
            INPRestHttpHelper httpClient, IConfiguration configuration
           )
        {
            _nPRestHttp = httpClient;
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _esbSFGetUrl2 = configuration["Nippon:ESB:sfToDoUrl"];
        }

        public async Task SyncJDData()
        {
            await SyncPickListOptions(); // 同步职位分类、专业类、专业,function job的下拉列表
            await SyncCustJDJobOptions(); // 获取标准岗位序列下拉列表
            await SyncJD(); // 获取JD内容
        }

        #region 通用接口：同步DOA审批角色
        /// <summary>
        /// 同步职位分类、专业类、专业的下拉列表
        /// </summary>
        /// <returns></returns>
        public async Task<string> SyncPickListOptions()
        {
            string msgResult = "---- SyncPickListOptions  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_Picklist_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFPickResultDto> needUpdates = new List<SFPickResultDto>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    Thread.Sleep(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$filter"":""picklistId in 'POSITION_CLASSIFICATION','ProfessionalCategories','Professional','Job Function'"",""$select"":""picklistId,picklistOptions/externalCode,picklistOptions/id,picklistOptions/status,picklistOptions/picklistLabels/label,picklistOptions/picklistLabels/locale,picklistOptions/picklistLabels/picklistOption/parentPicklistOption/picklistLabels/optionId"",""$expand"":""picklistOptions/picklistLabels/picklistOption/parentPicklistOption/picklistLabels""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFResponseDto<SFPickResultDto>>("http://esb.nipponpaint.com.cn/esb/sf/get/comm/api", requestBody, dic);
                    count = result?.Data?.Results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        needUpdates.AddRange(result?.Data?.Results);
                    }
                }

                if (needUpdates.Count() > 0)
                {
                    List<SFPickListOptionEntity> options = new List<SFPickListOptionEntity>();
                    foreach (var item in needUpdates)
                    {
                        foreach (var option in item.PicklistOptions.Results)
                        {
                            SFPickListOptionEntity sFPickListOption = new SFPickListOptionEntity() { Type = item.PicklistId, Id = Guid.NewGuid().ToString() };
                            sFPickListOption.Code = option.ExternalCode;
                            sFPickListOption.Status = option.Status.ToUpper() == "ACTIVE" ? 1 : 0;
                            sFPickListOption.Label = option.PicklistLabels.Results?.FirstOrDefault()?.Label;
                            sFPickListOption.OptionId = option.OptionId;
                            sFPickListOption.ParentOptionId = option.PicklistLabels.Results?.FirstOrDefault()?.PicklistOption?.ParentPickListOption?.PicklistLabels?.Results?.FirstOrDefault()?.OptionId;

                            options.Add(sFPickListOption);
                        }
                    }

                    var types = new string[] { "POSITION_CLASSIFICATION", "ProfessionalCategories", "Professional", "Job Function" };
                    _db.Deleteable<SFPickListOptionEntity>().Where(t => types.Contains(t.Type)).ExecuteCommand();
                    msgResult += "成功插入数" + _db.Insertable(options).ExecuteCommand();
                    msgResult += "|成功插入数" + JsonConvert.SerializeObject(options);
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncPickListOptions  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 获取标准岗位序列下拉列表
        /// </summary>
        /// <returns></returns>
        private async Task<string> SyncCustJDJobOptions()
        {
            string msgResult = "---- SyncCustJDJobOptions  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_CustJDJobFamily_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFCustJDJobDto> needUpdates = new List<SFCustJDJobDto>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    Thread.Sleep(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$select"":""externalCode,effectiveStartDate,createdDateTime,lastModifiedDateTime,externalName_zh_CN,mdfSystemStatus""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFResponseDto<SFCustJDJobDto>>(_esbSFGetUrl2, requestBody, dic);
                    count = result?.Data?.Results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        needUpdates.AddRange(result?.Data?.Results);
                    }
                }

                if (needUpdates.Count() > 0)
                {
                    List<SFPickListOptionEntity> options = new List<SFPickListOptionEntity>();
                    foreach (var item in needUpdates)
                    {
                        SFPickListOptionEntity sFPickListOption = new SFPickListOptionEntity() { Type = "JDJob", Id = Guid.NewGuid().ToString() };
                        sFPickListOption.Code = item.ExternalCode;
                        sFPickListOption.Status = item.Status.ToUpper() == "A" ? 1 : 0;
                        sFPickListOption.Label = item.ExternalName_zh_CN;
                        options.Add(sFPickListOption);
                    }

                    _db.Deleteable<SFPickListOptionEntity>().Where(t => t.Type == "JDJob").ExecuteCommand();
                    _db.Insertable(options).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncCustJDJobOptions  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 获取获取EC的标岗下拉列表
        /// </summary>
        /// <returns></returns>
        private async Task<List<SFFoJDJobDto>> SyncFoJobCodeOptions()
        {
            string msgResult = "---- SyncFoJobCodeOptions  Success  ---------";
            List<SFFoJDJobDto> needUpdates = new List<SFFoJDJobDto>();
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_FOJobCode_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    Thread.Sleep(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$select"":""lastModifiedDateTime,externalCode,startDate,name,name_zh_CN,description,cust_JDJobFamily,cust_Department,parentJobCode,cust_jobcodegroup,status,cust_suggestedduration,cust_promotion,cust_rotation,cust_JobFunction""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFResponseDto<SFFoJDJobDto>>(_esbSFGetUrl2, requestBody, dic);
                    count = result?.Data?.Results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        needUpdates.AddRange(result?.Data?.Results);
                    }
                }

                if (needUpdates.Count() > 0)
                {
                    List<SFPickListOptionEntity> options = new List<SFPickListOptionEntity>();
                    foreach (var item in needUpdates)
                    {
                        SFPickListOptionEntity sFPickListOption = new SFPickListOptionEntity() { Type = "FOJob", Id = Guid.NewGuid().ToString() };
                        sFPickListOption.Code = item.ExternalCode;
                        sFPickListOption.Status = item.Status.ToUpper() == "A" ? 1 : 0;
                        sFPickListOption.Label = item.NameZN ?? item.Name; // 取标岗中文名
                        sFPickListOption.LastModifiedDateTime = ToSFDateTime(item.LastModifiedDateTime);
                        item.LastModifiedDateTime = sFPickListOption.LastModifiedDateTime.ToString();
                        options.Add(sFPickListOption);
                    }

                    var lastModifiedDateTime = await _db.Queryable<SFPickListOptionEntity>().Where(t => t.Type == "FOJob").MaxAsync(t => t.LastModifiedDateTime);
                    var modefiedData = needUpdates.Where(t => Convert.ToDateTime(t.LastModifiedDateTime) >= lastModifiedDateTime);
                    if (modefiedData.Any())
                    {
                        var departMents = _dbPlatform.Queryable<Organizations>().Select(t => new OrgDto { Name = t.Name, DeptCode = t.DeptCode }).ToList();
                        departMents.Add(new OrgDto { Name = "区域公司", DeptCode = "00000000" });

                        foreach (var item in modefiedData)
                        {
                            TalentProfileDescribeEntity error = new TalentProfileDescribeEntity();
                            error.Id = Guid.NewGuid().ToString();
                            error.Type = "FOJobSyncLog";
                            error.Content = string.Empty;
                            error.TalentProfileId = item.ExternalCode;
                            var talentProfileEntity = await _db.Queryable<TalentProfileEntity>().Where(t => t.ExternalCode == item.ExternalCode).FirstAsync();
                            if (talentProfileEntity == null)
                            {
                                talentProfileEntity.TalentProfileId = Guid.NewGuid().ToString();
                                talentProfileEntity.CreateTime = ToSFDateTime(item.LastModifiedDateTime);
                                talentProfileEntity.LastModifiedDateTime = talentProfileEntity.CreateTime;
                                talentProfileEntity.CreateUserName = "管理员";
                                talentProfileEntity.CreateWorkNumber = "admin";
                                talentProfileEntity.ExternalCode = item.ExternalCode;
                                BuildStandardPositions(talentProfileEntity, options, departMents, item, error);
                                await _db.Insertable(talentProfileEntity).ExecuteCommandAsync();
                            }
                            else
                            {
                                BuildStandardPositions(talentProfileEntity, options, departMents, item, error);
                                await _db.Updateable(talentProfileEntity).ExecuteCommandAsync();
                            }

                            if (!error.Content.IsNullOrEmpty())
                            {
                                await _db.Insertable(error).ExecuteCommandAsync();
                            }
                        }
                    }

                    await _db.Deleteable<SFPickListOptionEntity>().Where(t => t.Type == "FOJob").ExecuteCommandAsync();
                    await _db.Insertable(options).ExecuteCommandAsync();
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncFoJobCodeOptions  Failed  ---------" + ex.Message;
            }

            return needUpdates;
        }

        /// <summary>
        /// 同步SFJD内容
        /// </summary>
        /// <returns></returns>
        private async Task<string> SyncJD()
        {
            string msgResult = "---- SyncJD  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_JobProfile_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;

                var lastModifiedDateTime = await _db.Queryable<TalentProfileEntity>().MaxAsync(t => t.LastModifiedDateTime);
                List<SFJDRequestDto> needUpdates = new List<SFJDRequestDto>();

                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    Thread.Sleep(2000);
                    var requestBody = string.Empty;
                    if (lastModifiedDateTime == null)
                    {
                        requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$expand"": ""longDesciptions"", ""$format"":""json"",""$select"":""externalCode,lastModifiedDateTime,status,template,role,name_zh_CN,longDesciptions/externalCode,longDesciptions/JobProfile_externalCode,longDesciptions/lastModifiedDateTime,longDesciptions/desc_zh_CN,longDesciptions/desc_defaultValue,longDesciptions/sectionType,longDesciptions/status,longDesciptions/sectionId""}";
                    }
                    else
                    {
                        requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$expand"": ""longDesciptions"", ""$format"":""json"",""$select"":""externalCode,lastModifiedDateTime,status,template,role,name_zh_CN,longDesciptions/externalCode,longDesciptions/JobProfile_externalCode,longDesciptions/lastModifiedDateTime,longDesciptions/desc_zh_CN,longDesciptions/desc_defaultValue,longDesciptions/sectionType,longDesciptions/status,longDesciptions/sectionId"",""$filter"":""lastModifiedDateTime ge '" + lastModifiedDateTime?.ToString("yyyy-MM-ddTH:mm:ss") + @"'""}";
                        //requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$expand"": ""longDesciptions"", ""$format"":""json"",""$select"":""externalCode,lastModifiedDateTime,status,template,role,name_zh_CN,longDesciptions/externalCode,longDesciptions/JobProfile_externalCode,longDesciptions/lastModifiedDateTime,longDesciptions/desc_zh_CN,longDesciptions/desc_defaultValue,longDesciptions/sectionType,longDesciptions/status,longDesciptions/sectionId"",""$filter"":""externalCode ge '59000296'""}";
                    }

                    var result = await _nPRestHttp.ESBPostAsync<SFResponseDto<SFJDRequestDto>>(_esbSFGetUrl2, requestBody, dic);
                    count = result?.Data?.Results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        needUpdates.AddRange(result?.Data?.Results);
                    }
                }

                var fojobs = await SyncFoJobCodeOptions(); // 获取获取EC的标岗下拉列表
                _ = Task.Run(() =>
                {
                    // 解析丢给后台做
                    AnalysisJDProfile(needUpdates, fojobs);
                });
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncJD  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 将日期转成SF需要的str
        /// 注意，推送给SF的数据，日期要加8H
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string ToSFStr(DateTime date, bool IsPush = false)
        {
            if (date == null)
            {
                return "0";
            }

            if (IsPush)
            {
                date = date.AddHours(8);
            }

            DateTimeOffset dateTime = new DateTimeOffset(date);
            return string.Format("/Date({0})/", dateTime.ToUnixTimeMilliseconds());
        }

        /// <summary>
        /// 将SF日期转成DateTime
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public DateTime? ToSFDateTime(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }

            long timestamp = 0;
            str = str.Substring(6, 13);
            bool isTrue = long.TryParse(str, out timestamp);
            if (isTrue)
            {
                DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(timestamp);
                return dateTime;
            }
            else
            {
                return null;
            }
        }
        #endregion


        #region 个性化方法

        /// <summary>
        /// 解析JD内容
        /// </summary>
        /// <param name="needUpdates">同步过来的JD数据</param>
        private void AnalysisJDProfile(List<SFJDRequestDto> needUpdates, List<SFFoJDJobDto> fojobs)
        {
            var sectionMap = _db.Queryable<TalentProfileSectionMappingEntity>().ToDictionary(it => it.SectionName, it => it.SectionId);
            var options = _db.Queryable<SFPickListOptionEntity>().ToList();
            foreach (var item in needUpdates)
            {
                TalentProfileDescribeEntity error = new TalentProfileDescribeEntity
                {
                    Id = Guid.NewGuid().ToString(),
                    TalentProfileId = item.ExternalCode,
                    Type = "SyncError",
                    Content = string.Empty,
                    KeyIndex = 0,
                };

                bool isExist = false;
                try
                {
                    TalentProfileEntity talentProfileEntity = _db.Queryable<TalentProfileEntity>().Where(t => t.ExternalCode == item.ExternalCode).First();
                    List<TalentProfileDescribeEntity> descs = new List<TalentProfileDescribeEntity>();
                    List<TalentProfileIndicatorEntity> indicators = new List<TalentProfileIndicatorEntity>();
                    List<TalentProfileContactEntity> contacts = new List<TalentProfileContactEntity>();
                    List<TalentProfileLanguageEntity> languageAbilities = new List<TalentProfileLanguageEntity>();
                    List<TalentProfileMainDutyEntity> dutys = new List<TalentProfileMainDutyEntity>();
                    string id = string.Empty;
                    if (talentProfileEntity == null)
                    {
                        talentProfileEntity = new TalentProfileEntity();
                        talentProfileEntity.TalentProfileId = Guid.NewGuid().ToString();
                        talentProfileEntity.CreateTime = ToSFDateTime(item.LastModifiedDateTime);
                        talentProfileEntity.LastModifiedDateTime = talentProfileEntity.CreateTime;
                        talentProfileEntity.CreateUserName = "管理员";
                        talentProfileEntity.CreateWorkNumber = "admin";
                        talentProfileEntity.ExternalCode = item.ExternalCode;
                    }
                    else
                    {
                        isExist = true;
                        // 开始解析，当JD最后修改时间大于等于记录中的创建或者修改时间时，无需解析
                        if (item.Status == "I")
                        {
                            _db.Updateable<TalentProfileEntity>()
                                .SetColumns(t => t.Status == -1)
                                .SetColumns(t => t.StatusName == "停用")
                                .Where(t => t.ExternalCode == item.ExternalCode)
                                .ExecuteCommand();

                            continue;
                        }

                        // 如果检测到JD已经提交流程,那么就不可以再解析
                        if (talentProfileEntity.Status == 3)
                        {
                            continue;
                        }

                        talentProfileEntity.UpdateTime = ToSFDateTime(item.LastModifiedDateTime);
                        talentProfileEntity.LastModifiedDateTime = talentProfileEntity.CreateTime;
                        talentProfileEntity.UpdateUserName = "管理员";
                        talentProfileEntity.UpdateWorkNumber = "admin";
                    }

                    talentProfileEntity.Status = 4;
                    talentProfileEntity.StatusName = "已完成";

                    id = talentProfileEntity.TalentProfileId;
                    var fojob = fojobs.FirstOrDefault(t => t.ExternalCode == talentProfileEntity.ExternalCode);
                    talentProfileEntity.JobName = fojob.NameZN ?? fojob.Name; // 岗位名称取中文名
                    #region

                    item.LongDesciptions.Results.ForEach(desc =>
                    {
                        string descStr = desc.DescValue ?? desc.Desc;
                        if (!descStr.IsNullOrEmpty())
                        {
                            descStr = Regex.Replace(descStr, @"\s", "");
                            descStr = Regex.Replace(descStr, @"&nbsp;", "");
                            if (desc.SectionId == sectionMap["标准岗位"].ToString())
                            {

                            }
                            else if (sectionMap["岗位目的"].ToString() == desc.SectionId)
                            {
                                TalentProfileDescribeEntity target = BuildLangDesc(descStr, id, "Target", error);
                                descs.Add(target);
                            }
                            else if (sectionMap["主要职责"].ToString() == desc.SectionId)
                            {
                                dutys = BuildMainDuty(descStr, talentProfileEntity, options, error);
                            }
                            else if (sectionMap["重要的绩效衡量标准"].ToString() == desc.SectionId)
                            {
                                indicators = BuildIndicators(descStr, id, error);
                            }
                            else if (sectionMap["主要工作联系"].ToString() == desc.SectionId)
                            {
                                contacts = BuildContacts(descStr, id, error);
                            }
                            else if (sectionMap["教育背景"].ToString() == desc.SectionId)
                            {
                                BuildEducational(descStr, talentProfileEntity, options, error);
                            }
                            else if (sectionMap["语言能力"].ToString() == desc.SectionId)
                            {
                                languageAbilities = BuildLanguageAbillities(descStr, id, error);
                            }
                            else if (sectionMap["年龄上限"].ToString() == desc.SectionId)
                            {
                                talentProfileEntity.AgeLimit = BuildLangDesc(descStr, id, "年龄上限", error).Content;
                            }
                            else if (sectionMap["关键能力经验"].ToString() == desc.SectionId)
                            {
                                var abilities = BuildExperienceAbillities(descStr, id, error);
                                descs.AddRange(abilities);
                            }
                            else if (sectionMap["领导力/关键素能"].ToString() == desc.SectionId)
                            {
                                descs.Add(BuildLangDesc(descStr, id, "Leadership", error));
                            }
                            else if (sectionMap["其他（个性特征、职业素养等）"].ToString() == desc.SectionId)
                            {
                                descs.Add(BuildLangDesc(descStr, id, "Other", error));
                            }
                            else if (sectionMap["资质证书"].ToString() == desc.SectionId)
                            {
                                descs.Add(BuildLangDesc(descStr, id, "QualificationCert", error));
                            }
                            else if (sectionMap["业绩贡献"].ToString() == desc.SectionId)
                            {
                                descs.Add(BuildLangDesc(descStr, id, "AchievementContribution", error));
                            }
                            else if (sectionMap["任职期限"].ToString() == desc.SectionId)
                            {
                                // BuildTenure(descStr, talentProfileEntity, error);
                            }
                            else if (sectionMap["职业发展路径"].ToString() == desc.SectionId)
                            {
                                // BuildCareerPath(descStr, talentProfileEntity, error);
                            }
                        }
                    });

                    if (isExist)
                    {
                        _db.Deleteable<TalentProfileEntity>().Where(t => t.TalentProfileId == id).ExecuteCommand();
                        _db.Deleteable<TalentProfileDescribeEntity>().Where(t => t.TalentProfileId == id).ExecuteCommand();
                        _db.Deleteable<TalentProfileMainDutyEntity>().Where(t => t.TalentProfileId == id).ExecuteCommand();
                        _db.Deleteable<TalentProfileIndicatorEntity>().Where(t => t.TalentProfileId == id).ExecuteCommand();
                        _db.Deleteable<TalentProfileLanguageEntity>().Where(t => t.TalentProfileId == id).ExecuteCommand();
                        _db.Deleteable<TalentProfileContactEntity>().Where(t => t.TalentProfileId == id).ExecuteCommand();
                    }

                    _db.Insertable(talentProfileEntity).ExecuteCommand();
                    _db.Insertable(descs).ExecuteCommand();
                    _db.Insertable(dutys).ExecuteCommand();
                    _db.Insertable(indicators).ExecuteCommand();
                    _db.Insertable(languageAbilities).ExecuteCommand();
                    _db.Insertable(contacts).ExecuteCommand();

                    #endregion
                }
                catch (Exception ex)
                {
                    error.Content += $"|出错了{ex.Message}";
                }
                finally
                {
                    if (!error.Content.IsNullOrEmpty())
                    {
                        _db.Insertable(error);
                    }
                }

            }
            #endregion
        }

        /// <summary>
        /// 解析关键知识/能力经验
        /// </summary>
        /// <param name="content">正文</param>
        /// <param name="id">JD主键</param>
        /// <param name=""></param>
        /// <returns></returns>
        private List<TalentProfileDescribeEntity> BuildExperienceAbillities(string content, string id, TalentProfileDescribeEntity error)
        {
            List<TalentProfileDescribeEntity> abilities = new List<TalentProfileDescribeEntity>();
            try
            {
                var mainWorkMatches = new Regex(@"<p><b>(.*?)</b></p><ul>(.*?)</ul>").Matches(content);
                foreach (Match item in mainWorkMatches)
                {
                    var details = new Regex(@"<li><p>(.*?)</p></li>").Matches(item.Groups[0].Value);
                    int index = 1;
                    foreach (Match detail in details)
                    {
                        TalentProfileDescribeEntity contactEntity = new TalentProfileDescribeEntity
                        {
                            TalentProfileId = id,
                            Type = item.Groups[1].Value,
                            Id = Guid.NewGuid().ToString(),
                            Content = detail.Groups[1].Value,
                            KeyIndex = index,
                        };

                        if (contactEntity.Type == "业务经验")
                        {
                            contactEntity.Type = "BusinessExperience";
                        }
                        else if (contactEntity.Type == "管理经验")
                        {
                            contactEntity.Type = "ManageExperience";
                        }
                        else if (contactEntity.Type == "区域经验")
                        {
                            contactEntity.Type = "AreaExperience";
                        }
                        else
                        {
                            contactEntity.Type = "Ability";
                        }

                        index++;
                        abilities.Add(contactEntity);
                    }
                }
            }
            catch (Exception ex)
            {
                error.Content += $"|解析关键知识/能力经验报错,{ex.Message}";
            }

            return abilities;
        }

        /// <summary>
        /// 解析语言能力
        /// </summary>
        /// <param name="content">正文</param>
        /// <param name="id">JD主键</param>
        /// <param name=""></param>
        /// <returns></returns>
        private List<TalentProfileLanguageEntity> BuildLanguageAbillities(string content, string id, TalentProfileDescribeEntity error)
        {
            List<TalentProfileLanguageEntity> languageAbillities = new List<TalentProfileLanguageEntity>();
            try
            {
                content.Replace(":", "：");
                var languageAbillityMatchs = new Regex(@"<p><b>(.*?)</b>(.*?)</p>").Matches(content);
                int index = 1;
                foreach (Match item in languageAbillityMatchs)
                {
                    TalentProfileLanguageEntity language = new TalentProfileLanguageEntity
                    {
                        TalentProfileId = id,
                        LanguageType = item.Groups[1].Value,
                        LanguageAbilityId = Guid.NewGuid().ToString(),
                        LanguageLevel = item.Groups[2].Value,
                        KeyIndex = index
                    };

                    if (language.LanguageType.Contains("优选"))
                    {
                        language.LanguageAbilityRequired = "优选";
                    }
                    else
                    {
                        language.LanguageAbilityRequired = "必选";
                    }

                    language.LanguageType = Regex.Replace(language.LanguageType.Replace("（优选）", string.Empty).Replace("（必选）", string.Empty).Replace("：", string.Empty).Replace(":", string.Empty), @"\d", "");

                    index++;
                    languageAbillities.Add(language);
                }
            }
            catch (Exception ex)
            {
                error.Content += $"解析语言能力出错,{ex.Message}";
            }

            return languageAbillities;
        }

        /// <summary>
        /// 解析主要工作联系
        /// </summary>
        /// <param name="content">正文</param>
        /// <param name="id">JD主键</param>
        /// <param name=""></param>
        /// <returns></returns>
        private List<TalentProfileContactEntity> BuildContacts(string content, string id, TalentProfileDescribeEntity error)
        {
            List<TalentProfileContactEntity> contacts = new List<TalentProfileContactEntity>();
            try
            {
                content = content.Replace(":", "：");
                content = content.Replace("沟通内容", "联系内容");
                var mainWorkMatches = new Regex(@"<p><b>(.*?)</b></p><ul>(.*?)</ul>").Matches(content);
                foreach (Match item in mainWorkMatches)
                {
                    var details = new Regex(@"<li>联系对象：(.*?)</li><li>联系内容：(.*?)</li>").Matches(item.Groups[2].Value);
                    int index = 1;
                    foreach (Match detail in details)
                    {
                        TalentProfileContactEntity contactEntity = new TalentProfileContactEntity
                        {
                            TalentProfileId = id,
                            CommunicationType = item.Groups[1].Value,
                            ContactId = Guid.NewGuid().ToString(),
                            ContactObject = detail.Groups[1].Value,
                            ContactContent = detail.Groups[2].Value,
                            KeyIndex = index,
                            RowSpan = index == 1 ? details.Count : 0
                        };

                        index++;
                        contacts.Add(contactEntity);
                    }
                }
            }
            catch (Exception ex)
            {
                error.Content += $"解析重要的主要工作联系出错,{ex.Message}";
            }

            return contacts;
        }

        /// <summary>
        /// 解析重要的绩效衡量标准
        /// </summary>
        /// <param name="content">正文</param>
        /// <param name="id">JD主键</param>
        /// <param name=""></param>
        /// <returns></returns>
        private List<TalentProfileIndicatorEntity> BuildIndicators(string content, string id, TalentProfileDescribeEntity error)
        {
            List<TalentProfileIndicatorEntity> indicators = new List<TalentProfileIndicatorEntity>();
            try
            {
                var quotaMatches = new Regex(@"<p><b>\d(.*?)</b></p><ul>(.*?)</ul>").Matches(content);
                foreach (Match item in quotaMatches)
                {
                    var details = new Regex(@"<li><p>(.*?)</p></li>").Matches(item.Groups[0].Value);
                    int index = 1;
                    foreach (Match detail in details)
                    {
                        TalentProfileIndicatorEntity talentProfileIndicatorEntity = new TalentProfileIndicatorEntity
                        {
                            TalentProfileId = id,
                            IndicatorType = item.Groups[1].Value,
                            IndicatorId = Guid.NewGuid().ToString(),
                            IndicatorName = detail.Groups[1].Value,
                            KeyIndex = index
                        };

                        index++;
                        indicators.Add(talentProfileIndicatorEntity);
                    }
                }
            }
            catch (Exception ex)
            {
                error.Content += $"解析重要的绩效衡量标准出错,{ex.Message}";
            }

            return indicators;
        }

        /// <summary>
        /// 解析长文本
        /// </summary>
        /// <param name="content">长文本郑文文</param>
        /// <param name="id">JD主键</param>
        /// <param name="type">长文本类型</param>
        /// <param name="error">日志</param>
        /// <returns></returns>
        private TalentProfileDescribeEntity BuildLangDesc(string content, string id, string type, TalentProfileDescribeEntity error)
        {
            TalentProfileDescribeEntity desc = new TalentProfileDescribeEntity();
            try
            {
                string result = content.Replace("<p>", "").Replace("</p>", "");
                desc = new TalentProfileDescribeEntity
                {
                    Id = Guid.NewGuid().ToString(),
                    Type = type,
                    Content = result,
                    KeyIndex = 0,
                    TalentProfileId = id
                };
            }
            catch (Exception ex)
            {
                error.Content += $"|解析长文本{type}时出错：{ex.Message}";
            }

            return desc;
        }

        /// <summary>
        /// 解析主要职责数据
        /// </summary>
        /// <param name="desc">标岗正文</param>
        /// <param name="talentProfileEntity">JD基础类</param>
        /// <param name="options">选项</param>
        /// <param name="error">错误</param>
        /// <returns></returns>
        private List<TalentProfileMainDutyEntity> BuildMainDuty(string contentStr, TalentProfileEntity talentProfileEntity, List<SFPickListOptionEntity> options, TalentProfileDescribeEntity error)
        {
            List<TalentProfileMainDutyEntity> allDutys = new List<TalentProfileMainDutyEntity>();
            try
            {
                if (contentStr != null)
                {
                    contentStr = contentStr.Replace("<p>", string.Empty).Replace("</p>", string.Empty);

                    var groups = contentStr.Split("<b>");

                    int i = 1;
                    foreach (var duty in groups)
                    {
                        List<TalentProfileMainDutyEntity> tempdutys = new List<TalentProfileMainDutyEntity>();
                        if (duty.IsNullOrEmpty())
                        {
                            continue;
                        }

                        string mainDuty = string.Empty;
                        string reportManager = string.Empty;
                        string reportManagerCode = string.Empty;
                        string groupId = Guid.NewGuid().ToString();
                        var dutyMatchs = new Regex(@"主要职责：(.*?)<br").Matches(duty);
                        if (!dutyMatchs.FirstOrDefault().Groups.IsNullOrEmpty() && dutyMatchs.FirstOrDefault().Groups.Count > 1)
                        {
                            mainDuty = dutyMatchs[0].Groups[1].Value;
                        }

                        var reportMatchs = new Regex("汇报主管：(.*?)</b>").Matches(duty);
                        if (!reportMatchs.FirstOrDefault().Groups.IsNullOrEmpty() && reportMatchs.FirstOrDefault().Groups.Count > 1)
                        {
                            reportManager = reportMatchs[0].Groups[1].Value;
                            var option = options.FirstOrDefault(t => t.Label == reportManager && t.Type == "FOJob");
                            if (option == null)
                            {
                                error.Content += $"汇报主管{reportManager}未匹配到相应的Code\r\n";
                            }
                            else
                            {
                                reportManagerCode = option.Code;
                            }
                        }

                        MatchCollection workActivaties = new Regex(@"工作活动：(.*?)<br/>\d+责任角色：(.*?)<br/>\d").Matches(duty);

                        int j = 1;
                        foreach (Match workActive in workActivaties)
                        {
                            TalentProfileMainDutyEntity dutyEntity = new TalentProfileMainDutyEntity
                            {
                                MainDutyId = Guid.NewGuid().ToString(),
                                TalentProfileId = talentProfileEntity.TalentProfileId,
                                GroupId = groupId,
                                MainDuty = mainDuty,
                                ReportManager = reportManagerCode,
                                ReportManagerName = reportManager,
                                RowSpan = 0,
                                KeyIndex = j,
                                No = $"{i}.{j}"
                            };

                            j++;
                            dutyEntity.WorkActivity = workActive.Groups[1].Value;
                            dutyEntity.ResposbilityRole = workActive.Groups[2].Value.ToLower();

                            if (dutyEntity.ResposbilityRole.Contains("a") || dutyEntity.ResposbilityRole.Contains("A"))
                            {
                                dutyEntity.ResposbilityRoleName = "独立负责(a)";
                                dutyEntity.ResposbilityRole = "a";
                            }
                            else if (dutyEntity.ResposbilityRole.Contains("b") || dutyEntity.ResposbilityRole.Contains("B"))
                            {
                                dutyEntity.ResposbilityRoleName = "与人合作(b)";
                                dutyEntity.ResposbilityRole = "b";
                            }
                            else if (dutyEntity.ResposbilityRole.Contains("c") || dutyEntity.ResposbilityRole.Contains("C"))
                            {
                                dutyEntity.ResposbilityRoleName = "协助(c)";
                                dutyEntity.ResposbilityRole = "c";
                            }
                            else
                            {
                                error.Content += $"责任角色编码{dutyEntity.ResposbilityRole}不存在\r\n";
                            }

                            tempdutys.Add(dutyEntity);
                        }

                        if (!tempdutys.IsNullOrEmpty())
                        {
                            tempdutys[0].RowSpan = tempdutys.Count();
                            allDutys.AddRange(tempdutys);
                            i++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                error.Content += "|解析主要职责报错" + ex.Message;
            }
            return allDutys;
        }

        /// <summary>
        /// 解析职业发展路径
        /// </summary>
        /// <param name="desc">标岗正文</param>
        /// <param name="talentProfileEntity">JD基础类</param>
        /// <param name="error">错误</param>
        private void BuildCareerPath(string content, TalentProfileEntity talentProfileEntity, TalentProfileDescribeEntity error)
        {
            try
            {
                var mainWorkMatches = new Regex(@"<p><b>(.*?)</b></p><ul>(.*?)</ul>").Matches(content);
                foreach (Match item in mainWorkMatches)
                {
                    var details = new Regex(@"<li>(.*?)</li>").Matches(item.Groups[0].Value);
                    string tempStr = string.Empty;
                    foreach (Match detail in details)
                    {
                        string tempValue = detail.Groups[1].Value.Replace("<p>", string.Empty).Replace("</p>", string.Empty);
                        tempStr += detail.Groups[1].Value + "；";
                    }

                    if (item.Groups[1].Value.Contains("轮岗"))
                    {
                        talentProfileEntity.PositionName = tempStr.Remove(tempStr.Length - 1);
                    }
                    else
                    {
                        talentProfileEntity.PositionName2 = tempStr.Remove(tempStr.Length - 1);
                    }

                }
            }
            catch (Exception ex)
            {
                error.Content += "|解析职业发展路径报错" + ex.Message;
            }
        }


        /// <summary>
        /// 解析任职期限
        /// </summary>
        /// <param name="desc">标岗正文</param>
        /// <param name="talentProfileEntity">JD基础类</param>
        /// <param name="error">错误</param>
        private void BuildTenure(string desc, TalentProfileEntity talentProfileEntity, TalentProfileDescribeEntity error)
        {
            try
            {
                var educationMatchs = new Regex(@"<p>(.*?)年</p>").Match(desc);
                string content = educationMatchs.Groups[1].Value;
                talentProfileEntity.TenureValue = content.ToOurDecimal();
                if (talentProfileEntity.TenureValue == 5)
                {
                    talentProfileEntity.Tenure = "5年";
                }
                else if (talentProfileEntity.TenureValue == 3)
                {
                    talentProfileEntity.Tenure = "3年";
                }
                else
                {
                    talentProfileEntity.Tenure = "其他";
                }

            }
            catch (Exception ex)
            {
                error.Content += "|解析任职期限报错" + ex.Message;
            }
        }

        /// <summary>
        /// 解析教育背景数据
        /// </summary>
        /// <param name="desc">标岗正文</param>
        /// <param name="talentProfileEntity">JD基础类</param>
        /// <param name="options">options</param>
        /// <param name="error">错误</param>
        private void BuildEducational(string desc, TalentProfileEntity talentProfileEntity, List<SFPickListOptionEntity> options, TalentProfileDescribeEntity error)
        {
            try
            {
                var educationMatchs = new Regex(@"</b>(.*?)</p>").Matches(desc);
                talentProfileEntity.Education = educationMatchs[0].Groups[1].Value;
                string specialityCourseContent = educationMatchs[1].Groups[1].Value;
                var specialityCourses = specialityCourseContent.Split("；");
                foreach (var specialityCourse in specialityCourses)
                {
                    if (specialityCourse.IsNullOrEmpty())
                    {
                        break;
                    }

                    string code = string.Empty;
                    string tempContent = specialityCourse.Replace("（优选）", string.Empty).Replace("（必选）", string.Empty);
                    var details = tempContent.Split(",");
                    foreach (var detail in details)
                    {
                        SFPickListOptionEntity option = new SFPickListOptionEntity();
                        if (detail.Contains("-"))
                        {
                            var labels = detail.Split("-");
                            option = options.FirstOrDefault(t => t.Label == labels[1] && t.Type == "Professional");
                        }
                        else
                        {
                            option = options.FirstOrDefault(t => t.Label == detail && t.Type == "ProfessionalCategories");
                        }
                        if (option == null)
                        {
                            error.Content += $"{detail}未匹配到相应的专业\r\n";
                        }
                        else
                        {
                            code += $"{option.Code};";
                        }
                    }

                    if (!code.IsNullOrEmpty())
                    {
                        code = code.Remove(code.Length - 1); // 移除末尾的分号
                    }

                    if (specialityCourses.Contains("优选"))
                    {
                        talentProfileEntity.NoRequireProfessionalCategorieName = tempContent;
                        talentProfileEntity.NoRequireProfessionalCategorie = code;
                    }
                    else
                    {
                        talentProfileEntity.ProfessionalCategorieName = tempContent;
                        talentProfileEntity.ProfessionalCategorie = code;
                    }
                }
            }
            catch (Exception ex)
            {
                error.Content += "|解析教育背景数据报错" + ex.Message;
            }
        }


        /// <summary>
        /// 解析标准岗位数据
        /// </summary>
        /// <param name="talentProfileEntity">JD基础类</param>
        /// <param name="options">下拉选项</param>
        /// <param name="departMents">组织选项</param>
        /// <param name="fojob">标岗数据</param>
        /// <param name="error">错误</param>
        private void BuildStandardPositions(TalentProfileEntity talentProfileEntity, List<SFPickListOptionEntity> options, List<OrgDto> departMents, SFFoJDJobDto fojob, TalentProfileDescribeEntity error)
        {
            try
            {
                talentProfileEntity.JobName = fojob.NameZN ?? fojob.Name;
                talentProfileEntity.CustJobcodeGroup = fojob.CustJobcodeGroup;
                talentProfileEntity.DepartmentName = fojob.CustDepartment;
                talentProfileEntity.JobCategroy = fojob.CustJDJobFamily;
                talentProfileEntity.ParentJob = fojob.ParentJobCode;
                talentProfileEntity.JobFunction = fojob.CustJobFunction; // 写入标岗增加JOB function字段，去除cust type字段
                talentProfileEntity.TenureValue = fojob.CustSuggestedduration; // 写入标岗增加建议任职年限字段
                talentProfileEntity.PositionName2 = fojob.CustPromotion; // 写入标岗增加可晋升字段
                talentProfileEntity.PositionName = fojob.CustRotation; // 写入标岗增加可转岗字段


                if (talentProfileEntity.TenureValue == 5)
                {
                    talentProfileEntity.Tenure = "5年";
                }
                else if (talentProfileEntity.TenureValue == 3)
                {
                    talentProfileEntity.Tenure = "3年";
                }
                else
                {
                    talentProfileEntity.Tenure = "其他";
                }

                if (!talentProfileEntity.DepartmentName.IsNullOrEmpty())
                {
                    var departMnet = departMents.FirstOrDefault(t => t.Name == talentProfileEntity.DepartmentName);
                    if (departMnet == null)
                    {
                        error.Content += "所属部门未匹配到相应的Code\r\n";
                    }
                    else
                    {
                        talentProfileEntity.DepartMent = departMnet.DeptCode;
                    }
                }

                if (!talentProfileEntity.ParentJobName.IsNullOrEmpty())
                {
                    var option = options.FirstOrDefault(t => t.Label == talentProfileEntity.ParentJobName && t.Type == "FOJob");
                    if (option == null)
                    {
                        error.Content += "直接上级岗位未匹配到相应的Code\r\n";
                    }
                    else
                    {
                        talentProfileEntity.ParentJob = option.Code;
                    }
                }

                if (!talentProfileEntity.CustJobcodeGroup.IsNullOrEmpty())
                {
                    var option = options.FirstOrDefault(t => t.Code == talentProfileEntity.CustJobcodeGroup && t.Type == "POSITION_CLASSIFICATION");
                    if (option == null)
                    {
                        error.Content += "职位分类未匹配到相应的Code\r\n";
                    }
                    else
                    {
                        talentProfileEntity.CustJobcodeGroupName = option.Label;
                    }
                }
            }
            catch (Exception ex)
            {
                error.Content += "|解析标准岗位数据报错" + ex.Message;
            }
        }
    }
}